package com.by.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * date 2025/2/14 17:15
 * author bjj
 * decoration
 * version 1.0
 * since jdk11
 */
@Configuration
public class MvcConfig implements WebMvcConfigurer {
    /**
     * 配置静态资源的处理
     *
     * @param configurer
     */
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    /**
     * 配置文件上传解析器
     *
     * @return
     */
    @Bean
    public StandardServletMultipartResolver multipartResolver() {
        return new StandardServletMultipartResolver();
    }

    /**
     * 跨域配置
     */
    /*@Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")//拦截所有以api开头的请求
                .allowedOriginPatterns("*")  // ✅ 允许所有来源，同时兼容 allowCredentials
                .allowedMethods("GET", "POST", "DELETE", "PUT", "OPTIONS")//允许的方法访问
                .allowedHeaders("*")//允许所有的请求头访问
                .allowCredentials(true)// 允许发送Cookie
                .maxAge(3600);// 1小时内不需要再发送预检请求
    }*/
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();

        config.setAllowCredentials(false);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        config.setMaxAge(3600L);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        CorsFilter filter = new CorsFilter(source);
        return filter;
    }


}
